<template>
  <view class="details-container">
    <scroll-view scroll-y class="scroll-area">
      <view class="content">
        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <template v-else>
          <view class="card status-card">
            <view class="status-left">
              <uv-icon name="clock" :size="22" :color="'#FF6B35'" />
              <text class="status-text">{{ formatOll(orderDetail.status) }}</text>
            </view>
          </view>

          <view class="card map-card">
            <view class="map-main">
              <!-- 地图组件 -->
              <map
                id="orderMap"
                style="width: 100%;height: 400rpx"
                :latitude="mapCenter.latitude"
                :longitude="mapCenter.longitude"
                :markers="mapMarkers"
              ></map>
            </view>
          </view>

          <view class="card driver-card">
            <view class="driver-info">
              <view class="driver-avatar">
                <uv-avatar :src="userInfo.avatar" :size="50" shape="circle" />
              </view>
              <view class="driver-details">
                <text class="driver-name">{{ orderDetail.driver_username || '-' }}</text>
                <text class="driver-phone">{{ orderDetail.driver_mobile || '-' }}</text>
              </view>
            </view>
          </view>
          <view class="card address-card">
            <view class="addr-row">
              <uv-icon name="map-fill" :size="22" :color="'#FF6B35'" />
              <view class="addr-info">
                <text class="addr-label">派送地址</text>
                <text class="addr-text">{{ orderDetail.address_detail || '-' }}</text>
              </view>
              <view class="nav-btn" @click="openNavigation">
                <uv-icon name="arrow-up" :size="16" :color="'#FF6B35'" />
                <text class="nav-text">导航</text>
              </view>
            </view>
          </view>

          <view class="card product-card">
            <view class="product-left">
              <view class="oil-box">
                
                  <image :src="orderDetail.goods_image" mode="aspectFill" style="width: 100%; height: 100%;" />
              </view>
            </view>
            <view class="product-main">
              <view class="product-title">{{ orderDetail.goods_name || '-10#号汽油' }}</view>
              <view class="product-meta">用油量：{{ orderDetail.usage || 1 }}升</view>
            </view>
            <view class="product-price">¥{{ orderDetail.goods_price || '4080.05' }}</view>
          </view>

          <view class="card time-card">
            <view class="time-row">
              <text class="time-label">下单时间：</text>
              <text class="time-value">{{
                formatDateTime(orderDetail.order_time) || '2023.10.10 12:00'
              }}</text>
            </view>
            <view class="divider"></view>
            <view class="time-row">
              <text class="time-label">使用时间：</text>
              <text class="time-value">{{
                formatDateTime(orderDetail.use_time) || '2023.10.10 12:00'
              }}</text>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>

    <!-- <view class="footer">
      <uv-button
        text="去加油"
        type="primary"
        size="large"
        :custom-style="primaryBtn"
        @click="goToRefuel"
      />
    </view> -->
  </view>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRequest } from '@/api'
  import { UserInfoManager } from '@/utils/userInfo'
  import { formatDateTime } from '@/utils/dateTime'
  import { onLoad } from '@dcloudio/uni-app'
  const { API_JIDAN_DETAIL_GET,API_COMEON_GET} = useRequest()
  const userInfo = UserInfoManager.getUserInfo()
  const orderId = ref('')
  const orderDetail = ref<any>({})
  const loading = ref(false)

  // 地图相关数据
  const mapCenter = ref({
    latitude: 39.9042,
    longitude: 116.4074
  })

  const mapMarkers = ref<any[]>([])

  const primaryBtn = {
    width: '100%',
    height: '88rpx',
    borderRadius: '48rpx',
    backgroundColor: '#FF6B35',
    color: '#fff',
    fontSize: '32rpx',
    fontWeight: '600'
  }

 
  onLoad((options: Record<string, any>) => {
    const id = options?.id ?? options?.orderId
    if (id) {
      try {
        orderId.value = decodeURIComponent(String(id))
      } catch {
        orderId.value = String(id)
      }
    }
  })

  // 更新地图数据
  const updateMapData = () => {
    const { order_lat, order_lng } = orderDetail.value
    
    if (order_lat && order_lng) {
      // 设置地图中心点
      mapCenter.value = {
        latitude: order_lat,
        longitude: order_lng
      }
      
      // 设置地图标记
      mapMarkers.value = [
        {
          id: 1,
          latitude: order_lat,
          longitude: order_lng,
          title: '配送地址',
          width: 20,
          height: 30,
          callout: {
            content: orderDetail.value.address_detail || '配送地址',
            color: '#333',
            fontSize: 14,
            borderRadius: 4,
            bgColor: '#fff',
            padding: 8,
            display: 'ALWAYS'
          }
        }
      ]
    }
  }

  const getOrderDetail = async () => {
    if (!orderId.value) {
      uni.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      })
      return
    }
    loading.value = true
    try {
      const params = {
        id: orderId.value,
        isdriver: UserInfoManager.lastrole()
      }
      const res = await API_JIDAN_DETAIL_GET(params)
      if (res.code === 1) {
        orderDetail.value = res.data
        updateMapData()
      }
    } catch (error) {
     
    } finally {
      loading.value = false
    }
  }

  // 打开导航
  const openNavigation = () => {
    if (orderDetail.value.order_lat && orderDetail.value.order_lng) {
      // #ifdef APP-PLUS
      // APP环境下尝试多种地图应用
      openAppNavigation()
      // #endif
      
      // #ifndef APP-PLUS
      // 非APP环境使用系统默认地图
      openSystemMap()
      // #endif
    } else {
      uni.showToast({
        title: '暂无位置信息',
        icon: 'none'
      })
    }
  }

  // APP端打开导航 - 多地图支持
  const openAppNavigation = () => {
    const lat = orderDetail.value.order_lat
    const lng = orderDetail.value.order_lng
    const address = orderDetail.value.address_detail || '配送地址'
    const encodedAddress = encodeURIComponent(address)
    
    // 检查已安装的地图应用
    const checkMaps = [
      {
        name: '高德地图',
        package: 'com.autonavi.minimap',
        urls: [
          `amapuri://route/plan/?dlat=${lat}&dlon=${lng}&dname=${encodedAddress}&dev=0&t=0`,
          `amapuri://poi?name=${encodedAddress}&lat=${lat}&lon=${lng}`
        ]
      },
      {
        name: '百度地图',
        package: 'com.baidu.BaiduMap',
        urls: [
          `baidumap://map/direction?destination=${lat},${lng}&mode=driving&src=webapp.baidu.openAPIdemo`,
          `baidumap://map/marker?location=${lat},${lng}&title=${encodedAddress}&content=${encodedAddress}&src=webapp.baidu.openAPIdemo`
        ]
      },
      {
        name: '腾讯地图',
        package: 'com.tencent.map',
        urls: [
          `qqmap://map/routeplan?type=drive&to=${encodedAddress}&tocoord=${lat},${lng}&referer=oilapp`,
          `qqmap://map/marker?marker=coord:${lat},${lng};title:${encodedAddress}&referer=oilapp`
        ]
      }
    ]
    
    let currentMapIndex = 0
    let currentUrlIndex = 0
    
    const tryOpenMap = () => {
      if (currentMapIndex >= checkMaps.length) {
        console.log('所有地图应用都尝试失败，使用系统地图')
        openSystemMap()
        return
      }
      
      const currentMap = checkMaps[currentMapIndex]
      
      if (currentUrlIndex >= currentMap.urls.length) {
        console.log(`${currentMap.name}所有URL都尝试失败，尝试下一个地图`)
        currentMapIndex++
        currentUrlIndex = 0
        tryOpenMap()
        return
      }
      
      const url = currentMap.urls[currentUrlIndex]
      console.log(`尝试打开${currentMap.name}方式${currentUrlIndex + 1}:`, url)
      
      try {
        plus.runtime.openURL(url)
        
        // 延迟检查是否成功打开
        setTimeout(() => {
          currentUrlIndex++
          tryOpenMap()
        }, 2000)
        
      } catch (error) {
        console.log(`${currentMap.name}方式${currentUrlIndex + 1}失败:`, error)
        currentUrlIndex++
        tryOpenMap()
      }
    }
    
    tryOpenMap()
  }

  // 打开系统默认地图
  const openSystemMap = () => {
    uni.openLocation({
      latitude: Number(orderDetail.value.order_lat),
      longitude: Number(orderDetail.value.order_lng),
      name: orderDetail.value.address_detail || '配送地址',
      address: orderDetail.value.address_detail || '配送地址',
      scale: 18
    })
  }

  // 去加油
  const goToRefuel = async() => {
    if (!orderId.value) {
      uni.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      })
      return
    }

    try {
      const params = {
        isdriver: UserInfoManager.lastrole(),
        id: orderId.value
      }

      const res = await API_COMEON_GET(params)
      if (res.code === 1) {
        uni.showToast({ title: '操作成功', icon: 'success' })
        setTimeout(() => {
          uni.$emit('refOrderList')
          setTimeout(() => {
            uni.navigateBack()
          }, 100)
        }, 500)
      } 
    } catch (error) {
      
    }
  }

  // 格式化订单状态
  const formatOll = (status: string) => {
    const statusMap: Record<string, string> = {
      pending: '待接单',
      delivery: '配送中',
      cancelled: '已取消',
      comeon: '加油中',
      pendingpay: '待付款',
      completed: '已完成'
    }

    return statusMap[status] || '未知状态'
  }

  onMounted(() => {
    getOrderDetail()
  })
</script>

<style lang="scss" scoped>
  .details-container {
    min-height: 100vh;
    background: #f6f7f9;
    display: flex;
    flex-direction: column;
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 100rpx 0;
  }

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }

  /* 将横向内边距放在 .content，保证左右一致 */
  .scroll-area {
    flex: 1;
    padding: 20rpx 0;
    padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
  }

  .content {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    padding: 0 24rpx;
  }

  .card {
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
    padding: 24rpx;
  }

  .status-card {
    display: flex;
    align-items: center;
    background: linear-gradient(to bottom, #fff5e9 0%, #fff 100%);
  }
  .status-left {
    display: flex;
    align-items: center;
    gap: 12rpx;
  }
  .status-text {
    font-size: 30rpx;
    color: #333;
    font-weight: 600;
  }

  .map-card {
    position: relative;
    overflow: hidden;
  }

  .map-main {
    position: relative;
    height: 400rpx;
  }

  .map-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #e3f2fd, #bbdefb);
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .map-tip {
    color: #1976d2;
    font-size: 28rpx;
  }

  .map-info-panel {
    position: absolute;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12rpx;
    padding: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10rpx);
  }

  .arrival-time {
    top: 20rpx;
    right: 20rpx;
    min-width: 200rpx;
  }

  .fastest-pickup {
    bottom: 20rpx;
    left: 20rpx;
    min-width: 280rpx;
  }

  .time-info {
    display: flex;
    flex-direction: column;
    gap: 4rpx;
    margin-bottom: 8rpx;
  }

  .time-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #ff6b35;

    &.green {
      color: #4caf50;
    }
  }

  .time-label {
    font-size: 22rpx;
    color: #666;
  }

  .location-info {
    display: flex;
    align-items: center;
    gap: 8rpx;
  }

  .location-text {
    font-size: 24rpx;
    color: #333;
    font-weight: 500;
  }

  .location-sub {
    font-size: 20rpx;
    color: #666;
  }

  .map-reference {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
  }

  .reference-text {
    font-size: 20rpx;
    color: #999;
  }

  .driver-card .driver-info {
    display: flex;
    align-items: center;
    gap: 20rpx;
  }

  .driver-avatar {
    flex-shrink: 0;
  }

  .driver-details {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
  }

  .driver-name {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }

  .driver-phone {
    font-size: 28rpx;
    color: #666;
  }

  .address-card .addr-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
  .addr-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 6rpx;
  }
  .addr-label {
    font-size: 28rpx;
    color: #8c8c8c;
  }
  .addr-text {
    font-size: 30rpx;
    color: #1f1f1f;
    font-weight: 500;
  }

  .nav-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4rpx;
    padding: 12rpx;
    border-radius: 50%;
    background: #f8f9fa;
  }

  .nav-text {
    font-size: 20rpx;
    color: #ff6b35;
  }

  .product-card {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
  .oil-box {
    width: 120rpx;
    height: 120rpx;
    border-radius: 16rpx;
    background: #fff5f0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .oil-box .oil-tag {
    margin-top: 8rpx;
    font-size: 32rpx;
    font-weight: 700;
    color: #1f1f1f;
  }
  .product-main {
    flex: 1;
  }
  .product-title {
    font-size: 34rpx;
    font-weight: 700;
    color: #1f1f1f;
    margin-bottom: 8rpx;
  }
  .product-meta {
    font-size: 28rpx;
    color: #8c8c8c;
  }
  .product-price {
    font-size: 34rpx;
    font-weight: 700;
    color: #ff6b35;
  }

  .time-card .time-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 18rpx 0;
  }
  .time-card .divider {
    height: 1rpx;
    background: #f0f0f0;
  }
  .time-label {
    font-size: 28rpx;
    color: #8c8c8c;
  }
  .time-value {
    font-size: 30rpx;
    color: #1f1f1f;
  }

  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom));
    background: #fff;
    box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);
  }
</style>
